package nd.privatebrowser;

import java.util.ArrayList;

import android.os.AsyncTask.Status;
import android.os.Bundle;

public class BrowserContext {
		
	private ArrayList<String> webHistory = new ArrayList<String>();
	private int historyInd;
	private String content;
	private String renderedUrl;
	private PageLoaderTask task;
	PrivateBrowserActivity activity;
	
	public BrowserContext(PrivateBrowserActivity activity) {
		this.activity = activity;
		this.historyInd = 0;
	}
	
	
	public void setCurrentPage(String content, String url, boolean isBack) {
		if(renderedUrl != null && isBack == false) {
			addWebHistory(this.renderedUrl);
		}
		this.content = content;
		this.renderedUrl = url;
	}
	
//	public void saveState(Bundle outState) {
//		outState.putString("pageContent", content);
//		outState.putString("pageUrl", renderedUrl);
//		outState.putStringArrayList("webHistory", webHistory);
//	}
//	
//	public void load(Bundle savedInstanceState) {
//		content = savedInstanceState.getString("pageContent");
//		renderedUrl = savedInstanceState.getString("pageUrl");
//		webHistory = savedInstanceState.getStringArrayList("webHistory");
//	}
	
	private void addWebHistory(String url) {
		if(historyInd >= webHistory.size()) {
			webHistory.add(url);
		} else {
			webHistory.set(historyInd, url);
			webHistory.subList(0, historyInd);
		}
		
		historyInd = webHistory.size();
	}
	
	public boolean hasHistory() {
		return webHistory.size()>=1 && historyInd > 0;
	}
	
	public String getContent() {
		return content;
	}
	public String getRenderedUrl() {
		return renderedUrl;
	}

	public void startTask(PageLoaderTask task) {
		if(this.task != null && this.task.getStatus() != Status.FINISHED) {
			this.task.cancel(true);
		}
		this.task = task;
		this.task.execute();
		
		activity.updateGoButtonText(false);
	}
	
	public void goBack() {
		
		String prevUrl = webHistory.get(historyInd-1);
		historyInd--;
		
        PageLoaderTask task = new PageLoaderTask(activity, prevUrl);
        task.setBack(true);
    	startTask( task );
	}


	public void cancelTask() {
		if(this.task != null) {
			this.task.cancel(true);
			activity.updateGoButtonText(true);
		}
	}


	public void clearWindowAndHistory() {
		cancelTask();
		this.task = null;
		webHistory.clear();
		content = null;
		renderedUrl = null;
	}


	public boolean isLoadingInProgress() {
		if(task != null && task.getStatus() == Status.RUNNING && 
				task.isCancelled()==false) {
			return true;
		}
		return false;
	}

}
